<template>
  <div>
    <div class="project" v-if="!projectAddShow && !contractDtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:marketingProjects:query']"
          class="btn search"
          @click="getProjectList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="projectName">项目名称</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectCode">项目编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectCategoryName">项目种类</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectTypeName">项目类型</el-checkbox>
            </div>
            <div>
              <el-checkbox label="executiveAddress">项目执行地</el-checkbox>
            </div>
            <div>
              <el-checkbox label="companyName">所属公司</el-checkbox>
            </div>

            <div>
              <el-checkbox label="businessName">业务人员</el-checkbox>
            </div>
            <div>
              <el-checkbox label="businessScheduleName">商务进度</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectStatusName">项目状态</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item">
          <el-input
            clearable
            v-model.trim="params.projectNameOrCode"
            class="search-input"
            maxlength="30"
            placeholder="请输入项目名称/编号查询"
          ></el-input>
        </div>
        <div class="search-item">
          <el-tree-select
            class="search-input"
            style="height: 100%"
            v-model="params.deptId"
            :data="deptList"
            :props="{
              value: 'deptId',
              label: 'deptName',
              children: 'children',
            }"
            value-key="deptId"
            placeholder="所属部门"
            check-strictly
            clearable
            :render-after-expand="false"
          />
        </div>
        <div class="search-item">
          <el-select
            v-model="params.projectCategory"
            placeholder="请选择项目种类"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in kindList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.projectType"
            placeholder="请选择项目类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in statusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.businessSchedule"
            placeholder="请选择商务进度"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in scheduleList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.includeContract"
            placeholder="请选择是否签约合同"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in contractList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
        <div class="search-item">
          <el-select
            v-model="params.projectStatus"
            placeholder="请选择项目状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in statusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="projectList"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <!-- 操作模式 -->
        <el-table-column
          label="操作"
          :show-overflow-tooltip="true"
          :width="'180px'"
        >
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-hasPermi="['system:marketingProjects:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>
              <el-icon
                v-hasPermi="['system:marketingProjects:follow']"
                title="跟进"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('follow', row)"
              >
                <DocumentChecked />
              </el-icon>
              <el-icon
                v-hasPermi="['system:marketingProjects:progress']"
                title="进度"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('schedule', row)"
              >
                <DArrowRight />
                <!-- <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                /> -->
              </el-icon>
              <el-icon
                v-if="
                  route.name === 'MarketingProjects' &&
                  [0, 5].includes(row.checkStatus)
                "
                v-hasPermi="['system:marketingProjects:delete']"
                title="删除"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
              <el-icon
                v-if="route.name === 'MarketingProjects' && row.isRole"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="70"
          align="center"
        />
        <el-table-column
          label="项目名称"
          prop="projectName"
          v-if="checkList.includes('projectName')"
          :show-overflow-tooltip="true"
          sortable="custom"
        />
        <el-table-column
          label="项目编号"
          prop="projectCode"
          v-if="checkList.includes('projectCode')"
          :show-overflow-tooltip="true"
          width="180"
          sortable="custom"
        />
        <el-table-column
          label="项目种类"
          prop="projectCategoryName"
          v-if="checkList.includes('projectCategoryName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="项目类型"
          prop="projectTypeName"
          v-if="checkList.includes('projectTypeName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="项目执行地"
          prop="executiveAddress"
          v-if="checkList.includes('executiveAddress')"
          :show-overflow-tooltip="true"
          width="200"
          sortable="custom"
        />
        <el-table-column
          label="商务进度"
          prop="businessScheduleName"
          v-if="checkList.includes('businessScheduleName')"
          :show-overflow-tooltip="true"
          width="100"
        />

        <el-table-column
          label="项目状态"
          prop="projectStatusName"
          v-if="checkList.includes('projectStatusName')"
          :show-overflow-tooltip="true"
          width="120"
          sortable="custom"
        />
        <el-table-column
          label="所属公司"
          prop="companyName"
          v-if="checkList.includes('companyName')"
          :show-overflow-tooltip="true"
          width="140"
          sortable="custom"
        />
        <el-table-column
          label="所属部门"
          v-if="checkList.includes('deptName')"
          prop="deptName"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        />
        <el-table-column
          label="业务人员"
          prop="businessName"
          v-if="checkList.includes('businessName')"
          :show-overflow-tooltip="true"
          width="100"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getProjectList"
      />
    </div>
    <ProjectAdd
      v-if="projectAddShow"
      ref="projectAddRef"
      v-model:projectAddShow="projectAddShow"
      @updateFollowAddShow="followAddShow = false"
      @refreshList="getProjectList"
      :pageType="pageType"
    />
    <ContractDtl
      ref="contractDtlRef"
      v-else
      v-if="contractDtlShow"
      v-model:contractDtlShow="contractDtlShow"
      @updateFollowAddShow="followAddShow = false"
      @refreshList="getProjectList"
      :pageType="pageType"
    />
    <el-dialog
      title="跟进记录填报"
      v-model="followAddShow"
      width="800px"
      append-to-body
    >
      <FollowAdd
        v-if="followAddShow"
        ref="followAddRef"
        v-model:followAddShow="followAddShow"
        @refreshList="getProjectList"
        :pageType="pageType"
      />
    </el-dialog>

    <!-- 进度弹窗 -->
    <el-dialog
      title=""
      v-model="showschedule"
      width="1400px"
      append-to-body
      class="dialogBox"
    >
      <Schedule
        v-if="showschedule"
        ref="showscheduleRef"
        v-model:followAddShow="showschedule"
        :rowdata="rowdata"
      />
      <template #footer>
        <!--  class="customer-info" -->

        <div class="dialog-footer">
          <el-button
            style="color: #fff; background-color: rgba(67, 207, 124, 1)"
            @click="handlescheduleAdd"
            >保存</el-button
          >

          <el-button
            style="background-color: #fff"
            @click="handlescheduleBack()"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import FollowAdd from "./followAdd.vue";
import ProjectAdd from "./projectAdd.vue";
import ContractDtl from "./dtl.vue";
import Schedule from "./schedule";
// import {
//   getProjectListApi,
//   deleteProjectApi,
//   revokeProjectApi,
//   getProjectCheckListApi,
// } from "@/api/sales/project";
import { getMarketingProjectList } from "@/api/sales/marketing.js";
import { getDictsApi } from "@/api/dict";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { listDeptAll } from "@/api/system/dept";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
// 路由
const route = useRoute();
// 搜索参数
const params = reactive({
  projectNameOrCode: null, // 项目编号
  deptId: null, //所属公司
  projectCategory: null, // 项目种类
  projectType: null, // 	项目类型
  businessSchedule: null,
  includeContract: null, //是否签合同
  projectStatus: null, // 项目状
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});

const checkList = ref([
  "projectCode",
  "projectName",
  "projectStatusName",
  "projectCategoryName",
  "projectTypeName",
  "executiveAddress",
  "includeContractName",
  "planContractTime",
  "checkStatusName",
  "nextNodeName",
  "deptName",
  "createUserName",
  "businessName",
  "createTime",
]);

// 表格加载效果
const loading = ref(false);
// 项目新增组件显隐
const projectAddShow = ref(false);
// 跟进新增组件显隐
const followAddShow = ref(false);
// 项目列表
const projectList = ref([]);
// 总数
const total = ref(0);
// 项目新增组件引用
const projectAddRef = ref(null);
// 跟进组件引用
const followAddRef = ref(null);
// 操作类型
const pageType = ref("");
// 审核状态列表
const checkListOptions = ref([]);
// 是否签合同列表
const contractList = ref([]);
// 项目种类列表
const kindList = ref([]);
// 项目状态列表
const statusList = ref([]);
// 商务进度列表
const scheduleList = ref([]);
// 项目类型列表
const typeList = ref([]);
// 部门类型列表
const deptList = ref([]);

const contractDtlShow = ref(false);
const contractDtlRef = ref(null);

//进度详情的显隐
let showschedule = ref(false);

let rowdata = ref(null);
// 处理进度保存
let showscheduleRef = ref(null);
const handlescheduleAdd = () => {
  console.log("jjj");
  showscheduleRef.value.handleraddbusSchedule();
};
const handlescheduleBack = () => {
  showschedule.value = false;
};
/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 60,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 60,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 获取项目列表
 */
const getProjectList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    let res = await getMarketingProjectList({ pageNum, pageSize }, params);
    projectList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    projectNameOrCode: null, // 项目编号
    deptId: null, //所属公司
    projectCategory: null, // 项目种类
    projectType: null, // 	项目类型
    businessSchedule: null,
    includeContract: null, //是否签合同
    projectStatus: null, // 项目状
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getProjectList();
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getProjectList();
};
/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      projectAddShow.value = true;
      nextTick(() => {
        projectAddRef.value.handleDetailInfo(row.projectId);
      });
      break;
    case "detail":
      pageType.value = type;
      contractDtlShow.value = true;
      nextTick(() => {
        contractDtlRef.value.handleDetailInfo(row);
        // followAddRef.value.handleDetailInfo(row.projectId);
      });
      break;

    case "schedule":
      rowdata.value = row;
      pageType.value = type;
      showschedule.value = true;
      break;
    case "follow":
      pageType.value = type;
      followAddShow.value = true;

      nextTick(() => {
        followAddRef.value.handleDetailInfo(row);
      });
      break;

    default:
      break;
  }
};

/**
 * @description: 获取字典
 */
async function getDicts() {
  await getDictsApi("erp_project_check_status").then((res) => {
    // 审核状态
    if (res.code === 200) {
      checkListOptions.value = res.data;
    }
  });

  await getDictsApi("erp_include_contract").then((res) => {
    // 是否签合同
    if (res.code === 200) {
      contractList.value = res.data;
    }
  });
  await getDictsApi("erp_project_category").then((res) => {
    // 项目种类
    if (res.code === 200) {
      kindList.value = res.data;
    }
  });
  await getDictsApi("erp_project_new_status").then((res) => {
    // 项目状态
    if (res.code === 200) {
      statusList.value = res.data;
    }
  });
  await getDictsApi("erp_project_type").then((res) => {
    // 项目类型
    if (res.code === 200) {
      typeList.value = res.data;
    }
  });
  await getDictsApi("erp_business_schedule").then((res) => {
    // 商务进度
    if (res.code === 200) {
      scheduleList.value = res.data;
    }
  });
  //部门
  listDeptAll().then((response) => {
    deptList.value = proxy.handleTree(response.data, "deptId");
  });
}

/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}

onMounted(() => {
  getTableHeader();
  // 路由携带项目id参数，直接显示详情页
  if (route.query?.projectId) {
    let projectId = route.query.projectId;
    pageType.value = "detail";
    projectAddShow.value = true;
    followAddShow.value = true;
    nextTick(() => {
      projectAddRef.value.handleDetailInfo(projectId);
      followAddRef.value.handleDetailInfo(projectId);
    });
  }
  if (route.query?.businessId) {
    let applyId = route.query.businessId;
    if (
      route.query.checkStatus === "待审核" ||
      route.query.checkStatus === "审核中"
    ) {
      pageType.value = "check";
      projectAddShow.value = true;
      followAddShow.value = true;
      nextTick(() => {
        projectAddRef.value.handleDetailInfo(Number(applyId));
        followAddRef.value.handleDetailInfo(Number(applyId));
      });
    }
  }
  if (route.query?.myinfoId) {
    let applyId = route.query.myinfoId;

    pageType.value = "detail";
    projectAddShow.value = true;
    followAddShow.value = true;
    nextTick(() => {
      projectAddRef.value.handleDetailInfo(Number(applyId));
      followAddRef.value.handleDetailInfo(Number(applyId));
    });
  }
  getProjectList();
  getDicts();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
.dialogBox .el-dialog__body {
  padding: 0px 20px !important;
}
</style>
<style lang="scss" scoped>
.project {
  padding: 20px;
  width: 100%;
  height: 100%;
  .search {
    flex-wrap: wrap;
    .search-item {
      margin-bottom: 10px;
    }
    .search-item:last-child {
      margin-bottom: 0px;
    }
  }
  .pagination {
    margin-top: 20px;
  }
}
</style>
